package org.file5.controller.admin;

import javax.servlet.http.HttpServletRequest;

import org.file5.domain.Category;
import org.file5.service.ServiceFascade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

@Controller
@RequestMapping("/admin/article/category/edit")
@SessionAttributes("category")
public class EditArticleCategoryForm {
	@Autowired
	private ServiceFascade sf;

	@InitBinder
	public void setAllowedFields(WebDataBinder dataBinder) {
		dataBinder.setDisallowedFields(new String[] { "uid" });
	}

	@RequestMapping(method = RequestMethod.GET)
	public String setupForm(@RequestParam("uid") String categoryId,
			ModelMap model) {
		Category category = this.sf.getBaseService().find(Category.class,
				categoryId);
		model.addAttribute("category", category);
		return "admin/article/categoryedit";
	}

	@RequestMapping(method = { RequestMethod.PUT, RequestMethod.POST })
	public String processSubmit(
			@ModelAttribute("category") Category category,
			BindingResult result, SessionStatus status,
			HttpServletRequest request) {

		// new PetValidator().validate(category, result);
		if (result.hasErrors()) {
			return "admin/article/categoryedit";
		} else {
			category = sf.getBaseService().addUpdate(category);
			status.setComplete();
			return "redirect:/admin/article/categories.htm";
		}
	}
}
